package com.example.wx.controller;

import com.example.wx.utils.SHA1;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@RestController
@RequestMapping("/wx")
public class WxController
{
    private static final Log log= LogFactory.getLog(WxController.class);
    public static final String TOKEN = "zhbcm";

    @GetMapping("/init")
    public void init(HttpServletRequest req, HttpServletResponse resp) throws NoSuchAlgorithmException, IOException
    {
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr = req.getParameter("echostr");
        String[] arr = {WxController.TOKEN, timestamp, nonce};
        Arrays.sort(arr);
        StringBuilder builder = new StringBuilder();
        for (String s : arr)
        {
            builder.append(s);
        }
        String sha1 = SHA1.sha1(builder.toString());
        if (sha1.equals(signature))
        {
            PrintWriter pw = resp.getWriter();
            pw.println(echostr);
            pw.flush();
            pw.close();
            log.info("接入成功！");
        } else
        {
            log.error("接入失败！");
        }
    }
}
